import time

from config.config import SeleniumConfig


class SocialMediaBase:
    def __init__(self, driver, base_url):
        self.Type = None
        self.interval = SeleniumConfig.interval  # 间隔
        self.simpleTime = SeleniumConfig.simpleTime  # 简单等待时间
        self.uploadTimeout = SeleniumConfig.uploadTimeout  # 上传超时时间
        self.loginTimeout = SeleniumConfig.loginTimeout  # 登录超时时间
        # self.cache_folder_name = SeleniumConfig.cache_folder_name  # 缓存目录，用来存储临时文件
        # os.makedirs(self.cache_folder_name, exist_ok=True)  # 创建缓存文件夹
        self.base_url = base_url  # 发布后台（若登录则可以进入，用来监测登录状态，并发布内容初始页）
        self.driver = driver

        self.driver.implicitly_wait(SeleniumConfig.timeout)  # 隐式等待

    def set_cookies(self, cookies):
        """
        设置cookies
        :param cookies: cookies
        :return: 是否设置成功(cookies是否有效)
        """
        self.driver.get(self.base_url)
        self.driver.delete_all_cookies()  # 清空token
        for cookie in cookies:  # 注入新token
            try:
                self.driver.add_cookie(cookie)
            except:
                print(f"注入cookie：{cookie}失败")
                pass
        self.driver.get(self.base_url)  # 尝试打开后台
        time.sleep(self.simpleTime)
        return self.driver.current_url == self.base_url  # 若无法打开后台(重定向)则说明cookies失效

    def get_cookies(self):
        """
        获取cookies,执行登录逻辑
        :return: cookies
        """
        self.driver.get(self.base_url)
        time.sleep(self.simpleTime)
        self.driver.delete_all_cookies()
        # 执行特定的登录逻辑
        is_login = self.perform_login()
        if not is_login: raise Exception("登录失败")
        time.sleep(self.simpleTime)
        cookies = self.driver.get_cookies()
        print("登录成功 cookie为:", cookies)
        return cookies

    def perform_login(self):
        raise NotImplementedError("子类必须实现此方法以完成登录逻辑")

    def is_login(self):
        """
        是否登录
        :return: 是否登录
        """
        self.driver.get(self.base_url)
        time.sleep(self.simpleTime)
        return self.driver.current_url == self.base_url
